{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Running Median\n",
    "\n",
    "[原题](https://mp.weixin.qq.com/s/hlABtdKBw73uI0C4MwI7Cg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Question\n",
    "\n",
    "You are given a stream of numbers. Compute the median for each new element."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Example\n",
    "\n",
    "```text\n",
    "Input: [2, 1, 4, 7, 2, 0, 5]\n",
    "Output: [2, 1.5, 2, 3, 2, 2, 2]\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def running_median(stream):\n",
    "    ''' Main Algorithm '''\n",
    "    \n",
    "    # Create a result list.\n",
    "    result = []\n",
    "    \n",
    "    # Create a temporary list.\n",
    "    temp = []\n",
    "    \n",
    "    # Traverse the stream.\n",
    "    for elem in stream:\n",
    "        # Push into the temporary list and sort ascendingly.\n",
    "        temp.append(elem)\n",
    "        temp.sort()\n",
    "        \n",
    "        # Get the median element of the list.\n",
    "        division = len(temp) // 2\n",
    "        \n",
    "        # Check if the amount of the list is odd or even.\n",
    "        if len(temp) % 2 == 1:\n",
    "            result.append(temp[division])\n",
    "        else:\n",
    "            result.append((temp[division - 1] + temp[division]) / 2)\n",
    "    \n",
    "    # Print out the result.\n",
    "    print(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2, 1.5, 2, 3.0, 2, 2.0, 2]\n"
     ]
    }
   ],
   "source": [
    "''' Test Scripts '''\n",
    "running_median([2, 1, 4, 7, 2, 0, 5])\n",
    "# 2 1.5 2 3.0 2 2.0 2"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
